﻿Imports System.Threading
Imports System.Timers
Imports HslCommunication
Imports HslCommunication.LogNet
Imports HslCommunication.Profinet.Melsec

Public Class ucLHJ

    Private WithEvents TmDB As System.Timers.Timer
    Private WithEvents tmPLC As System.Timers.Timer
    Private _status As LHJ_STATUS
    Private _row As Integer
    Private _col As Integer
    Private _equipID As String
    Private _prodID As String
    Private _RowCol As String
    Private _info As String

    '-------------
    Private _serverIp As String
    Private _serverPort As String
    Private _lhjIp As String
    Private _lhjPort As String
    Private _spec_ID As String

    Private _plcDataAddress As String = GetIniFile("PLC", "plcDataAddress", "", g_szInitFileName) '温度14个，压力1个
    Private _plcLHStatus As String = GetIniFile("PLC", "plcLHStatus", "", g_szInitFileName)   '处于第几个硫化区间
    Private _plcLHDtLen As String = GetIniFile("PLC", "plcLHDtLen", "", g_szInitFileName)     '某个区间的加热时长
    Private _plcSYSJ As String = GetIniFile("PLC", "plcSYSJ", "", g_szInitFileName) '剩余时长
    Private _plcZLHSJ As String = GetIniFile("PLC", "plcZLHSJ", "", g_szInitFileName)  '总硫化时长
    Private _PlcZSC As String = GetIniFile("PLC", "PlcZSC", "", g_szInitFileName)  '总计时
    Private _PlcSMYL As String = GetIniFile("PLC", "plcSMYL", "", g_szInitFileName)  '总计时

    Private _interval As Integer
    Private fx3uPLC As MelsecA1ENet
    Private PLC_CONNECTED As Boolean = False

    '-------------
    Private _fatherOBJ As frmLHJList
    Private objEquip As New clsHWSetting
    Private _LimitNum As Integer = 5
    'Public _ParentForm As Form

    Private _logFile As ILogNet
    Dim resetEventPLC As New ManualResetEvent(False)
    Dim resetEventDB As New ManualResetEvent(False)
    Dim objWriteLog As Object

    Private thReadPLCParam As Thread

    Private _BeginTime As DateTime = Nothing '开始时间
    Private HourPrompt As Integer '小时记录
    Public Sub startMonitor()
        LogFile.WriteInfo(EquipID, "开始监控：" & Now)

        TmDB = New Timers.Timer(5000)
        TmDB.Enabled = True
        resetEventDB.Set()

        tmPLC = New Timers.Timer
        tmPLC.Enabled = False
        resetEventPLC.Set()

    End Sub
    Private Sub writeErrlog(_keyWord As String, _text As String)
        LogFile.WriteError(_keyWord, _text)
    End Sub
    Private Sub writeInfolog(_keyWord As String, _text As String)
        LogFile.WriteInfo(_keyWord, _text)
    End Sub
    Private Sub TmDB_Elapsed(sender As Object, e As ElapsedEventArgs) Handles TmDB.Elapsed
        resetEventDB.WaitOne()
        If _Server_Stop = False Then
            readLHJStatusFromDB()
        End If
    End Sub

    Private Sub tmPLC_Elapsed(sender As Object, e As ElapsedEventArgs) Handles tmPLC.Elapsed
        resetEventPLC.WaitOne()
        If _Server_Stop = False Then
            LogFile.WriteInfo(EquipID, "tmPLC_Elapsed：_Server_Stop = False:" & Now)
            readPLCandSaveData()
            If IsNothing(_BeginTime) = False Then
                '每小时进行一次播报----------------------------
                Dim _datediff As Double = Math.Floor(Math.Abs(DateDiff(DateInterval.Minute, _BeginTime, Now)) / 60) '只取整数部分，不四舍五入，舍弃小数
                If _datediff > HourPrompt Then
                    HourPrompt = HourPrompt + 1
                    '更新硬件表，使其实提示语音
                    setHour_prompt_flg(1)
                End If
            End If
            '===============================================
        Else
                LogFile.WriteError(EquipID, "tmPLC_Elapsed：_Server_Stop = true:" & Now)
        End If
    End Sub
    Public Sub New(status As LHJ_STATUS, row As String, col As String, Optional EquipID As String = "",
                   Optional prodid As String = "", Optional info As String = "")
        InitializeComponent()
        Dim objLHJ As New clsLHJWorkDetail
        Me.Status = status
        Me.EquipID = EquipID
        lblLHJ.Text = EquipID
        If prodid <> "" Then Me.ProdID = prodid
        _LimitNum = objLHJ.getErrorContinuoustimes
        If Not HslCommunication.Authorization.SetAuthorizationCode("e3e27344-1a9f-4d8b-b4fc-da5cae4b99bf") Then
            'writeErrlog(EquipID, "Communication没有授权，只能使用24小时。")
        End If
        If Not HslControls.Authorization.SetAuthorizationCode("ce5ade06-6f14-4b0d-b9c2-0d625664dc3f") Then
            'writeErrlog(EquipID, "Controls没有授权，只能使用24小时。")
        End If
        'TmDB.Start()

        'logFile = New LogNetDateTime(Application.StartupPath & "\\Logs", GenerateMode.ByEveryDay)
    End Sub

    Public Property Status As LHJ_STATUS
        Get
            Return _status
        End Get
        Set(value As LHJ_STATUS)
            _status = value
            Select Case value
                Case LHJ_STATUS.BUSY
                    'BackColor = Color.Green
                    'lblLHJ_No.ForeColor = Color.White
                    'lblRowCol.ForeColor = Color.White

                    lblStatus.BackColor = Color.Green
                    Info = "硫化中"
                Case LHJ_STATUS.EMPTY
                    'BackColor = Color.White
                    'lblLHJ_No.ForeColor = Color.Black
                    'lblRowCol.ForeColor = Color.Black
                    lblStatus.BackColor = Color.Silver
                    Info = "无任务"
                Case LHJ_STATUS.LOSE_CONNECT
                    'BackColor = Color.Silver
                    'lblLHJ_No.ForeColor = Color.White
                    'lblRowCol.ForeColor = Color.White
                    lblStatus.BackColor = Color.Brown
                    Info = "无法连接"

                Case LHJ_STATUS.WAIT_OUT
                    'BackColor = Color.Yellow
                    'lblLHJ_No.ForeColor = Color.Red
                    'lblRowCol.ForeColor = Color.Red
                    lblStatus.BackColor = Color.Blue
                    Info = "要出炉"
                Case LHJ_STATUS.ERR
                    'BackColor = Color.Red
                    'lblLHJ_No.ForeColor = Color.White
                    'lblRowCol.ForeColor = Color.White
                    lblStatus.BackColor = Color.Red
                    Info = "异常"
                Case LHJ_STATUS.REPAIRS
                    'BackColor = Color.Blue
                    'lblLHJ_No.ForeColor = Color.White
                    'lblRowCol.ForeColor = Color.White
                    lblStatus.BackColor = Color.DarkOrange
                    Info = "维修中"
            End Select
        End Set
    End Property

    Public Property Row As String
        Get
            Return _row
        End Get
        Set(value As String)
            _row = value
        End Set
    End Property

    Public Property Col As String
        Get
            Return _col
        End Get
        Set(value As String)
            _col = value
        End Set
    End Property

    Public Property EquipID As String
        Get
            Return _equipID
        End Get
        Set(value As String)
            _equipID = value
        End Set
    End Property

    Public Property RowCol As String
        Get
            Return _RowCol
        End Get
        Set(value As String)
            _RowCol = value
        End Set
    End Property

    Public Property Info As String
        Get
            Return _info
        End Get
        Set(value As String)
            _info = value

            If lblStatus.InvokeRequired Then
                Dim objSetInfo As New setInfoDelegate(AddressOf setInfo)
                Me.Invoke(objSetInfo, value)
            Else
                lblStatus.Text = value
            End If

            'lblLHJ_No.Text = value
        End Set
    End Property
    Private Sub setInfo(txt As String)
        lblStatus.Text = txt
    End Sub
    Delegate Sub setInfoDelegate(txt As String)
    Public Property ProdID As String
        Get
            Return _prodID
        End Get
        Set(value As String)
            _prodID = value

        End Set
    End Property
    Public Property Interval As Integer
        Get
            Return _interval
        End Get
        Set(value As Integer)
            _interval = value
        End Set
    End Property

    Public Property LhjIp As String
        Get
            Return _lhjIp
        End Get
        Set(value As String)
            _lhjIp = value
        End Set
    End Property

    Public Property LhjPort As Integer
        Get
            Return _lhjPort
        End Get
        Set(value As Integer)
            _lhjPort = value
        End Set
    End Property

    Public Property ServerIp As String
        Get
            Return _serverIp
        End Get
        Set(value As String)
            _serverIp = value
        End Set
    End Property

    Public Property ServerPort As String
        Get
            Return _serverPort
        End Get
        Set(value As String)
            _serverPort = value
        End Set
    End Property

    Public Property Spec_ID As String
        Get
            Return _spec_ID
        End Get
        Set(value As String)
            _spec_ID = value
        End Set
    End Property

    Public Property FatherOBJ As frmLHJList
        Get
            Return _fatherOBJ
        End Get
        Set(value As frmLHJList)
            _fatherOBJ = value
        End Set
    End Property

    Public Property LogFile As ILogNet
        Get
            Return _logFile
        End Get
        Set(value As ILogNet)
            _logFile = value
        End Set
    End Property

    Delegate Sub setDBNumEventHandler(_num As Integer)
    Delegate Sub setPLCNumEventHandler(_num As Integer)

    Private Sub setDBnum(_num As Integer)
        If _num = 0 Then
            HslLabel1.Text = 0
        Else
            HslLabel1.Text = IIf(HslLabel1.Text = "", 0, HslLabel1.Text) + _num
        End If

    End Sub
    Private Sub setPLCnum(_num As Integer)
        If _num = 0 Then
            lblNum.Text = 0
        Else
            lblNum.Text = IIf(lblNum.Text = "", 0, lblNum.Text) + _num
        End If

    End Sub


    Enum LHJ_STATUS
        EMPTY = 0 '空闲
        BUSY = 1 '工作中
        LOSE_CONNECT = 2 '失联
        WAIT_OUT = 3 '等待出炉
        ERR = 4 '有错误
        REPAIRS = 5 '维修
    End Enum

    Public Sub readLHJStatusFromDB()
        Try
            resetEventDB.Reset() '1110追加

            Dim objDBnum As New setDBNumEventHandler(AddressOf setDBnum)
            Me.Invoke(objDBnum, 1)
            Dim objPLCnum As New setDBNumEventHandler(AddressOf setPLCnum)

            'HslLabel1.Text = IIf(HslLabel1.Text = "", 0, HslLabel1.Text) + 1
            Dim objHWSetting As New clsHWSetting
            Dim _itl As Integer
            Dim dt As DataTable = objHWSetting.selectForLHJByID(g_ws_lh, _equipID)
            If dt.Rows.Count > 0 Then

                If dt.Rows(0)("status") = "0" Then
                    Status = LHJ_STATUS.EMPTY
                    tmPLC.Stop()
                    '更新硬件表，使其实提示语音
                    setHour_prompt_flg(0)
                    '------------追加PLC参数读取-------------20220818
                    READ_PLC_PARAM_FLG = False
                    '------------追加PLC参数读取-------------20220818
                    _itl = 0

                    Me.Invoke(objPLCnum, 0)
                Else

                    ProdID = DBNULLtoBlank(dt.Rows(0)("prod_id"))
                    Spec_ID = DBNULLtoBlank(dt.Rows(0)("prod_spec_id"))
                    _itl = objHWSetting.getSpecIntervalbySpecID(Spec_ID)
                    If dt.Rows(0)("status") = "1" Then

                        Status = LHJ_STATUS.BUSY

                    End If
                    If dt.Rows(0)("status") = "2" Then
                        _itl = 0
                        tmPLC.Stop()
                        '更新硬件表，使其实提示语音
                        setHour_prompt_flg(0)
                        '------------追加PLC参数读取-------------20220818
                        READ_PLC_PARAM_FLG = False
                        '------------追加PLC参数读取-------------20220818
                        Status = LHJ_STATUS.LOSE_CONNECT
                    End If
                    If dt.Rows(0)("status") = "3" Then
                        Status = LHJ_STATUS.WAIT_OUT

                    End If
                    If dt.Rows(0)("status") = "4" Then
                        ' _itl = 30 * 1000
                        Status = LHJ_STATUS.ERR

                    End If
                    If tmPLC.Interval <> _itl Or tmPLC.Enabled = False Then

                        tmPLC.Stop()
                        '更新硬件表，使其实提示语音
                        setHour_prompt_flg(0)
                        '------------追加PLC参数读取-------------20220818
                        READ_PLC_PARAM_FLG = False
                        '------------追加PLC参数读取-------------20220818
                        If _itl > 0 Then
                            tmPLC.Interval = _itl
                            '每小时提示----------
                            HourPrompt = 0
                            _BeginTime = getBeginTime()
                            '--------------------
                            '连接&读取PLC--------
                            ConnectPLC()
                            readPLCandSaveData()
                            '--------------------
                            tmPLC.Start()
                            '------------追加PLC参数读取-------------20220818
                            thReadPLCParam = New Thread(AddressOf read_plc_param)
                            READ_PLC_PARAM_FLG = True
                            thReadPLCParam.Start()
                            '------------追加PLC参数读取-------------20220818
                        End If
                    End If
                End If
            End If

        Catch ex As Exception
            writeErrlog(EquipID, "readLHJStatusFromDB 错误:" & ex.Message)
        End Try
        resetEventDB.Set() '1110追加
    End Sub
    Private Sub ConnectPLC()
        fx3uPLC = New MelsecA1ENet(_lhjIp, _lhjPort)
        PLC_CONNECTED = fx3uPLC.ConnectServer().IsSuccess

        'fx3uPLC.SetPersistentConnection()

    End Sub
    Public Sub readPLCandSaveData()
        resetEventPLC.Reset() '1110追加
        Dim objPLCnum As New setDBNumEventHandler(AddressOf setPLCnum)
        Me.Invoke(objPLCnum, 1)

        Dim objLHJ As New clsLHJWorkDetail

        Try
            writeInfolog(EquipID, "开始")

            If ProdID = "" Then
                writeErrlog(EquipID, "readPLCandSaveData:没有ProdID")
                resetEventPLC.Set() '1110追加
                Exit Sub
            End If

            Dim readisSuccess As OperateResult(Of Short) = fx3uPLC.ReadInt16(_plcLHStatus)
            If readisSuccess.IsSuccess = False Then
                writeErrlog(EquipID, readisSuccess.ErrorCode & ":" & readisSuccess.Message)
                writeErrlog(EquipID, "重新连接")
                ConnectPLC()
            End If
            If PLC_CONNECTED = True Then 'fx3uPLC.ReadInt16(_plcLHStatus).IsSuccess = True Then

                writeInfolog(EquipID, "连接PLC成功")
                '读取寄存地址内的数据 BEGIN----------
                System.Threading.Thread.Sleep(500)
                '温度20个，压力1个
                Dim plcDataRes As OperateResult(Of Short()) = fx3uPLC.ReadInt16(_plcDataAddress, 14)
                Dim plcData(13) As Double

                System.Threading.Thread.Sleep(300)
                '处于第几个硫化区间
                Dim lhStatus As Short = fx3uPLC.ReadInt16(_plcLHStatus).Content

                'System.Threading.Thread.Sleep(300)
                ''某个区间的加热时长
                'Dim lhDtLen As Short = fx3uPLC.ReadInt16(_plcLHDtLen).Content

                System.Threading.Thread.Sleep(300)
                '剩余时间
                Dim _lhsysj As Short
                '硫化总时长
                Dim _zsc As Short
                '硫化时长  
                Dim _lhjsc As Short
                Dim plcTimeDataRes As OperateResult(Of Short()) = fx3uPLC.ReadInt16("D253", 3)
                If plcTimeDataRes.IsSuccess = True Then
                    _zsc = plcTimeDataRes.Content(0)
                    _lhsysj = plcTimeDataRes.Content(1)
                    _lhjsc = plcTimeDataRes.Content(2)
                    'If _lhsysj <> _zsc - _lhjsc Then
                    '    _lhsysj = _zsc - _lhjsc
                    'End If
                End If
                System.Threading.Thread.Sleep(300)
                Dim _smyl As Short = fx3uPLC.ReadInt16(_PlcSMYL).Content

                '读取寄存地址内的数据 END----------
                Dim enLH As New entity_LHDataInput

                If plcDataRes.IsSuccess = True Then
                    writeInfolog(EquipID, "温度20个，压力2个 读取成功")
                    '温度14个，压力1个
                    For i As Integer = 0 To plcData.Length - 1
                        plcData(i) = plcDataRes.Content(i)
                    Next

                    With enLH
                        .col_time = Now
                        .lhj_id = EquipID
                        .factory_id = g_factory_id
                        'PLC中的20个温度
                        .temp_val_1 = plcData(0) '上1
                        .temp_val_2 = plcData(1) '上2
                        .temp_val_3 = plcData(2) '上3
                        .temp_val_4 = plcData(3) '上4
                        .temp_val_5 = plcData(4) '下1
                        .temp_val_6 = plcData(5) '下2
                        .temp_val_7 = plcData(6) '下3
                        .temp_val_8 = plcData(7) '下4
                        .temp_val_9 = IIf(plcData(8) = 255, 0, plcData(8)) '中1
                        .temp_val_10 = IIf(plcData(9) = 255, 0, plcData(9)) '中2
                        .temp_val_11 = IIf(plcData(10) = 255, 0, plcData(10)) '中3
                        .temp_val_12 = IIf(plcData(11) = 255, 0, plcData(11)) '中4

                        .temp_val_13 = 0
                        .temp_val_14 = 0
                        .temp_val_15 = 0
                        .temp_val_16 = 0
                        .temp_val_17 = 0
                        .temp_val_18 = 0
                        .temp_val_19 = 0
                        .temp_val_20 = 0

                        'PLC中的压力
                        .pres_val1 = _smyl / 10 '锁模压力
                        .pres_val2 = plcData(13) / 10 '主缸压力

                        'PLC中的硫化时长
                        .lh_time_len = 0

                        .lhjsc = _lhjsc

                        .zsc = _zsc
                        .old_status = lhStatus
                        If lhStatus = 2 Or lhStatus = 3 Then
                            .status = 2
                        ElseIf lhStatus = 4 Or lhStatus = 5 Then
                            .status = 3
                        Else
                            .status = lhStatus
                        End If

                        If .lhsysj = .zsc Then
                            .lhsysj = 0
                        Else
                            .lhsysj = _lhsysj
                        End If

                        'If Status = LHJ_STATUS.BUSY Or Status = LHJ_STATUS.ERR Then
                        'ElseIf Status = LHJ_STATUS.WAIT_OUT Then
                        '    If _lhsysj <= objLHJ.getReadyOutMinute Then '小于规定时间（30）更新，否则 不更新
                        '        .lhsysj = _lhsysj
                        '    End If
                        'End If
                        .prod_id = _prodID
                        .update_time = Now
                        'If enLH.status <> 0 Then
                        Try

                            objLHJ.insertData(enLH)

                        Catch ex As Exception
                            writeErrlog(EquipID, "insertData 错误" & ex.Message)

                        End Try

                        Try
                            objEquip.setLHJSYSJ(EquipID, .lhsysj)

                        Catch ex As Exception
                            writeErrlog(EquipID, "setLHJSYSJ 错误" & ex.Message)
                        End Try
                        Try
                            objEquip.setProdInfoTime(_prodID, _zsc, .lhjsc)

                        Catch ex As Exception
                            writeErrlog(EquipID, "setProdInfoTime 错误" & ex.Message)
                        End Try
                        Try
                            setBusy(enLH) '不把温度、压力作为异常的判断标准
                            'End If
                        Catch ex As Exception
                            writeErrlog(EquipID, "setBusy 错误" & ex.Message)
                        End Try
                    End With

                    'Status = LHJ_STATUS.BUSY
                    'objEquip.setLHJStatus(EquipID, Status)
                    '_ParentForm.Refresh()
                    'fx3uPLC.ConnectClose()  '============删除======================
                Else
                    writeErrlog(EquipID, "温度20个，压力2个 读取失败")
                End If
            Else
                writeErrlog(EquipID, "fx3uPLC.ConnectServer失败 ：" & _lhjIp & ":" & _lhjPort)
                'writeErrlog(EquipID, readisSuccess.ErrorCode & ":" & readisSuccess.Message)
                'ConnectPLC()
                'readPLCandSaveData()
                'plcConnectFLg.IsSuccess = False
                'Status = LHJ_STATUS.LOSE_CONNECT
                'objEquip.setLHJStatus(EquipID, LHJ_STATUS.LOSE_CONNECT)
                'writeErrlog(EquipID, "UcLhj:（1）状态改为2")
                ''Dim rtn As Integer = objEquip.record_LHJ_Status(EquipID, 2)
                'LogFile.WriteInfo(EquipID & "--ucLHJ保存记录1=>", 2)
            End If

        Catch ex As Exception
            writeErrlog(EquipID, "readPLCandSaveData:" & ex.Message)
            writeErrlog(EquipID, "PLC连接失败2，关闭设备。")
            'plcConnectFLg.IsSuccess = False
            '连接失败
            Status = LHJ_STATUS.LOSE_CONNECT
            objEquip.setLHJStatus(EquipID, LHJ_STATUS.LOSE_CONNECT)
            writeErrlog(EquipID, "UcLhj:（2）状态改为2")
            'Dim rtn As Integer = objEquip.record_LHJ_Status(EquipID, 2)
            LogFile.WriteInfo(EquipID & "--ucLHJ保存记录2=>", 2)
            '============删除======================
            'Finally
            '    If IsNothing(plcConnectFLg) = False AndAlso plcConnectFLg.IsSuccess = True Then
            '        fx3uPLC.ConnectClose()
            '    End If
            '============删除======================
        End Try
        resetEventPLC.Set() '1110追加
    End Sub


    Private Sub setBusy(en As entity_LHDataInput)
        Try

            Dim objLHJ As New clsLHJWorkDetail
            Dim objProdSpec As New clsProdSpec
            Dim stStr As String = "0"
            '根据prod_id取得支座型号信息
            Dim objHWSetting As New clsHWSetting
            Dim dt As DataTable = objHWSetting.selectForLHJByID(g_ws_lh, _equipID)
            Dim _LH_Pres_Check_times As Integer = 0

            If dt.Rows.Count > 0 Then
                If dt.Rows(0)("status") = "0" Or dt.Rows(0)("prod_id") = "" Then
                    Exit Sub
                Else
                    stStr = dt.Rows(0)("status")
                End If
            ElseIf dt.Rows.Count = 0 Then
                Exit Sub
            End If
            '当是最终状态的时候，判断是否待出炉***********************************************
            'If en.status <> 0 And en.lhsysj <= objLHJ.getReadyOutMinute Then
            If _prodID <> "" And en.lhjsc > 0 And en.lhsysj <= objLHJ.getReadyOutMinute Then
                stStr = LHJ_STATUS.WAIT_OUT
            End If

            If Status = LHJ_STATUS.WAIT_OUT Then
                stStr = LHJ_STATUS.WAIT_OUT
            End If

            If stStr <> dt.Rows(0)("status") Then
                Status = stStr
                objEquip.setLHJStatus(EquipID, stStr)
                writeInfolog(EquipID, "UcLhj:状态从" & dt.Rows(0)("status") & "改为" & stStr)
            End If
            '**********************************************************************************
            '************************以下为温度、压力检测**************************************
            If en.old_status > 3 Then Exit Sub

            Dim dtSpec As DataTable = objProdSpec.getProdSpecInfo(ProdID)

            _LimitNum = objLHJ.getErrorContinuoustimes
            _LH_Pres_Check_times = getSysParam("LH_Pres_Check_times")

            '取得最近5条数据
            Dim dtLimit As DataTable = objLHJ.selectDetailByLimit(EquipID, ProdID, en.old_status, _LimitNum)


            If dtSpec.Rows.Count > 0 Then
                Dim dr As DataRow = dtSpec.Rows(0)

                If en.old_status <> 0 And en.lhjsc > 0 Then
                    If _LH_Pres_Check_times = 0 Then
                        'ElseIf _LH_Pres_Check_times = 1 Then
                        '    '锁模压力异常判断
                        '    If chkYL(en.pres_val1, dr("pres_max_val_" & en.old_status & "1")， dr("pres_min_val_" & en.old_status & "1")) = False Then
                        '        stStr = LHJ_STATUS.ERR
                        '        objLHJ.insertErr(en, 2, "锁模压力异常", "锁模压力：" & en.pres_val1 & " 超过上下限。（上限：" & dr("pres_max_val_" & en.old_status & "1") & "下限：" & dr("pres_min_val_" & en.old_status & "1") & "）")
                        '    End If
                        '    ''主缸压力异常判断
                        '    If chkYL(en.pres_val2, dr("pres_max_val_" & en.old_status & "2")， dr("pres_min_val_" & en.old_status & "2")) = False Then
                        '        stStr = LHJ_STATUS.ERR
                        '        objLHJ.insertErr(en, 2, "主缸压力异常", "主缸压力：" & en.pres_val2 & " 超过上下限。（上限：" & dr("pres_max_val_" & en.old_status & "2") & "下限：" & dr("pres_min_val_" & en.old_status & "2") & "）")
                        '    End If
                    ElseIf _LH_Pres_Check_times >= 1 Then

                        If dtLimit.Rows.Count >= _LH_Pres_Check_times Then
                            '锁模压力异常判断
                            'If chkYL(en.pres_val1, dr("pres_max_val_" & en.old_status & "1")， dr("pres_min_val_" & en.old_status & "1")) = False Then
                            Dim _FlgSM As Boolean = True
                            For i = 1 To _LH_Pres_Check_times
                                If i > dtLimit.Rows.Count Then Exit For
                                If chkYL(dtLimit.Rows(i - 1)("pres_val1"), dr("pres_max_val_" & en.old_status & "1")， dr("pres_min_val_" & en.old_status & "1")) = True Then
                                    _FlgSM = False
                                    Exit For
                                Else
                                    writeErrlog(EquipID, String.Format("SM{0}：MAX{1}：MIN{2}", dtLimit.Rows(i - 1)("pres_val1"), dr("pres_max_val_" & en.old_status & "1"), dr("pres_min_val_" & en.old_status & "1")))
                                End If
                            Next
                            If _FlgSM Then
                                stStr = LHJ_STATUS.ERR
                                objLHJ.insertErr(en, 2, "锁模压力异常", "锁模压力：" & en.pres_val1 & " 超过上下限。（上限：" & dr("pres_max_val_" & en.old_status & "1") & "下限：" & dr("pres_min_val_" & en.old_status & "1") & "）")
                            End If
                            'End If

                            ''主缸压力异常判断
                            'If chkYL(en.pres_val2, dr("pres_max_val_" & en.old_status & "2")， dr("pres_min_val_" & en.old_status & "2")) = False Then
                            Dim _FlgZG As Boolean = True
                            For i = 1 To _LH_Pres_Check_times
                                If i > dtLimit.Rows.Count Then Exit For
                                If chkYL(dtLimit.Rows(i - 1)("pres_val2"), dr("pres_max_val_" & en.old_status & "2")， dr("pres_min_val_" & en.old_status & "2")) = True Then
                                    _FlgZG = False
                                    Exit For
                                Else
                                    writeErrlog(EquipID, String.Format("ZG{0}：MAX{1}：MIN{2}", dtLimit.Rows(i - 1)("pres_val2"), dr("pres_max_val_" & en.old_status & "2")， dr("pres_min_val_" & en.old_status & "2")))
                                End If
                            Next
                            If _FlgZG Then
                                stStr = LHJ_STATUS.ERR
                                objLHJ.insertErr(en, 2, "主缸压力异常", "主缸压力：" & en.pres_val2 & " 超过上下限。（上限：" & dr("pres_max_val_" & en.old_status & "2") & "下限：" & dr("pres_min_val_" & en.old_status & "2") & "）")
                            End If
                            'End If
                        End If

                    End If
                End If
                Dim UpTemp As Double = en.temp_val_2
                Dim MidTemp As Double = en.temp_val_10
                Dim DnTemp As Double = en.temp_val_6

                '第一，二阶段判断连续
                If en.old_status = 1 Or en.old_status = 2 Then

                    '判断加热时间后第一个点是否在第二段上下限内
                    '0：不进行检查，1：进行加温检查 ，2：进行检查
                    Dim rtn As Integer = 2
                    If en.old_status = 2 Then

                        rtn = objLHJ.chkJR(EquipID, ProdID, en.old_status, CInt(dr("heatup1")), _LimitNum)
                        'If rtn = 1 Then
                        '    If chkWD(UpTemp, dr("temp_max_val_" & en.old_status), dr("temp_min_val_" & en.old_status)) = False Then
                        '        If stStr = LHJ_STATUS.BUSY Then
                        '            stStr = LHJ_STATUS.ERR
                        '        End If
                        '        objLHJ.insertErr(en, 1, "上模升温异常", "上模温度：" & UpTemp & " 超过上下限。（上限：" & dr("temp_max_val_" & en.old_status) & "下限：" & dr("temp_min_val_" & en.old_status) & "）")
                        '    End If
                        '    If chkWD(DnTemp, dr("temp_max_val_" & en.old_status), dr("temp_min_val_" & en.old_status)) = False Then
                        '        If stStr = LHJ_STATUS.BUSY Then
                        '            stStr = LHJ_STATUS.ERR
                        '        End If
                        '        objLHJ.insertErr(en, 1, "下模升温异常", "下模温度：" & DnTemp & " 超过上下限。（上限：" & dr("temp_max_val_" & en.old_status) & "下限：" & dr("temp_min_val_" & en.old_status) & "）")
                        '    End If

                        'End If
                    End If

                    If en.old_status = 1 Or rtn = 2 Then
                        '上下模温度判断
                        If dtLimit.Rows.Count = _LimitNum Then
                            '上模温度判断
                            Dim errUPFlg As Boolean = True
                            For Each drLmt As DataRow In dtLimit.Rows
                                '如果非连续则退出
                                If chkWD(drLmt("temp_val_2"), dr("temp_max_val_" & en.old_status), dr("temp_min_val_" & en.old_status)) = True Then
                                    errUPFlg = False
                                    Exit For
                                End If
                            Next
                            '当连续出现异常则报错
                            If errUPFlg = True Then
                                If stStr = LHJ_STATUS.BUSY Then
                                    stStr = LHJ_STATUS.ERR
                                End If
                                objLHJ.insertErr(en, 1, "上模温度异常", "上模温度连续" & _LimitNum & "次出现异常：" & UpTemp & " 超过上下限。（上限：" & dr("temp_max_val_" & en.old_status) & "下限：" & dr("temp_min_val_" & en.old_status) & "）")
                            End If

                            '下模温度判断
                            Dim errDNFlg As Boolean = True
                            For Each drLmt As DataRow In dtLimit.Rows
                                '如果非连续则退出
                                If chkWD(drLmt("temp_val_6"), dr("temp_max_val_" & en.old_status), dr("temp_min_val_" & en.old_status)) = True Then
                                    errDNFlg = False
                                    Exit For
                                End If
                            Next
                            '当连续出现异常则报错
                            If errDNFlg = True Then
                                If stStr = LHJ_STATUS.BUSY Then
                                    stStr = LHJ_STATUS.ERR
                                End If
                                objLHJ.insertErr(en, 1, "下模温度异常", "下模温度连续" & _LimitNum & "次出现异常：" & DnTemp & " 超过上下限。（上限：" & dr("temp_max_val_" & en.old_status) & "下限：" & dr("temp_min_val_" & en.old_status) & "）")
                            End If
                        End If

                        '中模温度判断(在设备的第二阶段)
                        If en.status = 2 Then
                            If dtLimit.Rows.Count = _LimitNum Then
                                Dim errMidFlg As Boolean = True
                                For Each drLmt As DataRow In dtLimit.Rows
                                    '如果非连续则退出
                                    If chkWD(drLmt("temp_val_10"), dr("temp_mid_max_val_2"), dr("temp_mid_min_val_2")) = True Then
                                        errMidFlg = False
                                        Exit For
                                    End If
                                Next
                                '当连续出现异常则报错
                                If errMidFlg = True Then
                                    If stStr = LHJ_STATUS.BUSY Then
                                        stStr = LHJ_STATUS.ERR
                                    End If
                                    objLHJ.insertErr(en, 1, "中模温度异常", String.Format("中模温度连续{0}次出现异常：{1} 超过上下限。（上限：{2}下限：{3}）", _LimitNum, MidTemp, dr("temp_mid_max_val_2"), dr("temp_mid_min_val_2")))
                                End If
                            End If
                        End If
                    End If
                ElseIf en.old_status = 3 Then '第三阶段为降温阶段，不用上下限判断

                    If dtLimit.Rows.Count = _LimitNum Then

                        If UpTemp >= dtLimit.Rows(dtLimit.Rows.Count - 1)("temp_val_2") Then
                            If chkWD(UpTemp, dr("temp_max_val_" & en.old_status), dr("temp_min_val_" & en.old_status)) = False Then

                                If stStr = LHJ_STATUS.BUSY Then
                                    stStr = LHJ_STATUS.ERR
                                End If
                                objLHJ.insertErr(en, 1, "上模降温异常", "上模温度：" & UpTemp & "没有持续下降")

                            End If
                        End If
                        If MidTemp >= dtLimit.Rows(dtLimit.Rows.Count - 1)("temp_val_10") Then
                            If chkWD(MidTemp, dr("temp_mid_max_val_" & en.old_status), dr("temp_mid_min_val_" & en.old_status)) = False Then

                                If stStr = LHJ_STATUS.BUSY Then
                                    stStr = LHJ_STATUS.ERR
                                End If
                                objLHJ.insertErr(en, 1, "中模降温异常", "中模温度：" & MidTemp & "没有持续下降")
                            End If
                        End If
                        If DnTemp >= dtLimit.Rows(dtLimit.Rows.Count - 1)("temp_val_6") Then
                            If chkWD(DnTemp, dr("temp_max_val_" & en.old_status), dr("temp_min_val_" & en.old_status)) = False Then
                                If stStr = LHJ_STATUS.BUSY Then
                                    stStr = LHJ_STATUS.ERR
                                End If
                                objLHJ.insertErr(en, 1, "下模降温异常", "下模温度：" & DnTemp & "没有持续下降")
                            End If
                        End If
                    End If
                End If

            End If

        Catch ex As Exception

            writeErrlog(EquipID, "setBusy ：" & ex.Message)
        End Try
    End Sub

    Private Function chkWD(wd As Double, sj_wd_Max As Double, sj_wd_Min As Double) As Boolean
        If wd > 0 Then
            If wd > sj_wd_Max Or wd < sj_wd_Min Then
                Return False
            Else
                Return True
            End If
        Else
            Return True
        End If
    End Function

    Private Function chkYL(yl As Double, sj_yl_Max As Double, sj_yl_min As Double) As Boolean
        If yl > 0 Then
            If yl > sj_yl_Max Or yl < sj_yl_min Then
                Return False
            Else
                Return True
            End If
        Else
            Return True
        End If
    End Function


    Private Sub TmDB_Disposed(sender As Object, e As EventArgs) Handles TmDB.Disposed
        DBacs.Disconnect()
        MyBase.Dispose()
    End Sub

    Private Sub tmPLC_Disposed(sender As Object, e As EventArgs) Handles tmPLC.Disposed
        DBacs.Disconnect()
        MyBase.Dispose()
    End Sub
    Private _Server_Stop As Boolean = False
    Public Sub StopServer()
        _Server_Stop = True

        fx3uPLC?.ConnectClose()

        'resetEventDB.WaitOne()
        'resetEventDB.Close()
        resetEventDB.Reset()
        resetEventPLC.Reset()
        tmPLC.Stop()

        '------------追加PLC参数读取-------------20220818
        READ_PLC_PARAM_FLG = False
        '------------追加PLC参数读取-------------20220818
        'resetEventPLC.WaitOne()
        'resetEventPLC.Close()
        TmDB.Stop()
    End Sub

    Private Sub lblLHJ_Click(sender As Object, e As EventArgs) Handles lblLHJ.Click, MyBase.Click, lblStatus.Click
        '硫化机组件点击事件
        If Status = LHJ_STATUS.BUSY Or Status = LHJ_STATUS.ERR Or Status = LHJ_STATUS.WAIT_OUT Then
            '只有状态“忙”的硫化机进行迁移
            '画面迁移
            Dim detail As New frmLHJDetail
            detail.LhjID = _equipID
            detail.ShowDialog()
        End If

    End Sub


    '------------------追加PLC参数读取-------------20220818
    ''' <summary>
    ''' 读PLC参数处理线程的flag:如true：保持循环，false：退出循环
    ''' </summary>
    Private READ_PLC_PARAM_FLG As Boolean = False

    ''' <summary>
    ''' 读设备里的设定参数等信息
    ''' </summary>
    Private Sub read_plc_param()
        Dim dtParam As DataTable = read_plc_param_info()
        Dim strParam As String = ""
        Dim paramValue As New Object
        Dim getAllowReadParam As String = getSysParam("READ_LHJ_PLC_PARAM") '得到Confng的设定值

        '如果开始 而且 系统config也允许
        While READ_PLC_PARAM_FLG And getAllowReadParam = "1"
            strParam = ""
            Try
                If dtParam.Rows.Count > 0 Then
                    For Each drParam As DataRow In dtParam.Rows

                        If drParam("types") = "boolean" Then
                            If fx3uPLC.ReadBool(drParam("address")).IsSuccess Then
                                paramValue = fx3uPLC.ReadBool(drParam("address")).Content
                            Else
                                paramValue = "NULL"
                            End If
                        ElseIf drParam("types") = "short" Then
                            If fx3uPLC.ReadInt16(drParam("address")).IsSuccess Then
                                paramValue = fx3uPLC.ReadInt16(drParam("address")).Content
                            Else
                                paramValue = "NULL"
                            End If

                        End If
                        strParam &= String.Format("{0}({1}):{2},", drParam("notes"), drParam("address"), paramValue.ToString)
                    Next

                    strParam = strParam.Substring(0, strParam.Length - 1)
                    If insertParam(strParam) = -2 Then
                        LogFile.WriteError(Me.EquipID & "：参数保存错误")
                    End If
                End If
            Catch ex As Exception
                LogFile.WriteError(Me.EquipID & "：" & ex.Message)
            End Try
            Thread.Sleep(500)
        End While
    End Sub

    Private Function read_plc_param_info() As DataTable
        Dim szSql As String = String.Empty
        szSql &= "SELECT * FROM sf.b_equip_lhj_param_info "

        Dim dt As DataTable = DBacs.ExecuteSql(szSql, -1)
        If IsNothing(dt) Then
            Return New DataTable
        Else
            Return dt
        End If
    End Function
    Private Function insertParam(strParam As String) As Integer
        Dim szSql As String = String.Empty
        '删除2天前的一条记录
        szSql = " delete from sf.b_equip_lhj_param "
        szSql &= " where savetime=(select savetime from sf.b_equip_lhj_param where lhj=? and update_time < ? limit 1)"
        DBacs.ExecuteUpdateSql(szSql, -1, Me.EquipID, Now.AddDays(-2))
        '追加一条记录
        szSql = "INSERT INTO sf.b_equip_lhj_param(savetime, lhj, prod_id, param_info,update_time) VALUES (?, ?, ?, ?, ?) "
        Dim _savetime As String = Now.Year & Now.Month & Now.Day & Now.Hour & Now.Minute & Now.Second & Now.Millisecond
        Return DBacs.ExecuteUpdateSql(szSql, -1, _savetime, Me.EquipID, Me.ProdID, strParam, Now)

    End Function
    '--------------------------------------------20220818

    ''' <summary>
    ''' 设定每小时提示Flg
    ''' </summary>
    ''' <param name="_flg">0:关，1:开</param>
    ''' <returns></returns>
    Private Function setHour_prompt_flg(_flg As Integer)
        Dim szSql As String = String.Empty

        If _flg = 0 Then _BeginTime = Nothing
        szSql = "update sf.t_hw_setting set hour_prompt_flg=? where factory_id=? and workshop_id=? and equip_type_id=? and equip_id=? "

        Return DBacs.ExecuteUpdateSql(szSql, -1, _flg, g_factory_id, g_ws_lh, g_equiptype_LHJ, EquipID)
    End Function
    Private Function getBeginTime() As DateTime
        Dim szSql As String = String.Empty
        szSql &= "SELECT into_vu_time FROM sf.b_prod_info where factory_id=? and prod_id=? "

        Dim dt As DataTable = DBacs.ExecuteSql(szSql, -1, g_factory_id, ProdID)
        If IsNothing(dt) OrElse dt.Rows.Count = 0 Then
            Return Nothing
        Else
            Return dt.Rows(0)("into_vu_time")
        End If
    End Function
End Class
